package com.atguigu.edu.realtime.app.dws;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import com.atguigu.edu.realtime.beans.TradeFullOrderBean;
import com.atguigu.edu.realtime.utils.DateFormatUtil;
import com.atguigu.edu.realtime.utils.MyClickhouseUtil;
import com.atguigu.edu.realtime.utils.MyKafkaUtil;

import org.apache.flink.api.common.eventtime.SerializableTimestampAssigner;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.common.functions.ReduceFunction;
import org.apache.flink.api.common.restartstrategy.RestartStrategies;
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend;
import org.apache.flink.streaming.api.CheckpointingMode;
import org.apache.flink.streaming.api.datastream.AllWindowedStream;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.CheckpointConfig;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.AllWindowFunction;
import org.apache.flink.streaming.api.windowing.assigners.TumblingEventTimeWindows;
import org.apache.flink.streaming.api.windowing.time.Time;
import org.apache.flink.streaming.api.windowing.windows.TimeWindow;
import org.apache.flink.util.Collector;


import java.time.Duration;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;


public class DwsTradeFullOrderWindow {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(4);
       /* //设置检查点
        env.enableCheckpointing(5000L, CheckpointingMode.EXACTLY_ONCE);
        //设置超时时间
        env.getCheckpointConfig().setCheckpointTimeout(6000L);
        //最小时间间隔
        env.getCheckpointConfig().setMinPauseBetweenCheckpoints(2000L);
        //job结束后检查点是否保存
        env.getCheckpointConfig().enableExternalizedCheckpoints(CheckpointConfig.ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION);
        //重启策略
        env.setRestartStrategy(RestartStrategies.failureRateRestart(3, Time.days(30),Time.seconds(3)));
        //设置状态后端
        env.setStateBackend(new HashMapStateBackend());
        env.getCheckpointConfig().setCheckpointStorage("hdfs://hadoop101:8020/edu/ck");
        //操作hadoop用户
        System.setProperty("HADOOP_USER_NAME","atguigu");*/

        //从kafka 主题读取数据
        String topic = "dwd_trade_order_detail";
        String groupId = "dwd_trade_full_order_group";
        DataStreamSource<String> KafkaStr = env.addSource(MyKafkaUtil.getKafkaConsumer(topic, groupId));
        //转换成实体对象
        SingleOutputStreamOperator<TradeFullOrderBean> fullOrderBeanDS = KafkaStr.map(new MapFunction<String, TradeFullOrderBean>() {
            @Override
            public TradeFullOrderBean map(String s) throws Exception {
                JSONObject jsonObject = JSON.parseObject(s);
                return TradeFullOrderBean.builder()
                        .orderIdSet(new ArrayList<>(Collections.singleton(jsonObject.getString("order_id"))))
                        .userIdSet(new HashSet<>(Collections.singleton(jsonObject.getString("user_id"))))
                        .orderAmount(jsonObject.getDouble("final_amount"))
                        .ts(jsonObject.getLong("od_ts") * 1000)
                        .build();
            }
        });
        // fullOrderBeanDS.print();

        //指定水位线
        SingleOutputStreamOperator<TradeFullOrderBean> waterMarkDS = fullOrderBeanDS.assignTimestampsAndWatermarks(WatermarkStrategy.<TradeFullOrderBean>forBoundedOutOfOrderness(Duration.ofSeconds(3)).withTimestampAssigner(new SerializableTimestampAssigner<TradeFullOrderBean>() {
            @Override
            public long extractTimestamp(TradeFullOrderBean tradeFullOrderBean, long l) {
                return tradeFullOrderBean.getTs();
            }
        }));

        //  waterMarkDS.print();
        //开窗 WindowedStream<TradProvinceOrderBean, String, TimeWindow> windowDS = keyedDS.window(TumblingEventTimeWindows.of(Time.seconds(10)));
        AllWindowedStream<TradeFullOrderBean, TimeWindow> windowDS = waterMarkDS.windowAll(TumblingEventTimeWindows.of(Time.seconds(10)));

        SingleOutputStreamOperator<TradeFullOrderBean> reduceDS = windowDS.reduce(new ReduceFunction<TradeFullOrderBean>() {
            @Override
            public TradeFullOrderBean reduce(TradeFullOrderBean v1, TradeFullOrderBean v2) throws Exception {
                v1.getOrderIdSet().addAll(v2.getOrderIdSet());
                v1.getUserIdSet().addAll(v2.getOrderIdSet());
                v1.setOrderAmount(v1.getOrderAmount() + v2.getOrderAmount());
                return v1;
            }
        }, new AllWindowFunction<TradeFullOrderBean, TradeFullOrderBean, TimeWindow>() {
            @Override
            public void apply(TimeWindow timeWindow, Iterable<TradeFullOrderBean> iterable, Collector<TradeFullOrderBean> collector) throws Exception {
                String stt = DateFormatUtil.toYmdHms(timeWindow.getStart());
                String edt = DateFormatUtil.toYmdHms(timeWindow.getEnd());
                for (TradeFullOrderBean tradeFullOrderBean : iterable) {
                    tradeFullOrderBean.setStt(stt);
                    tradeFullOrderBean.setEdt(edt);
                    tradeFullOrderBean.setTs(System.currentTimeMillis());
                    tradeFullOrderBean.setOrderCount((long) tradeFullOrderBean.getOrderIdSet().size());
                    tradeFullOrderBean.setUserCount((long) tradeFullOrderBean.getUserIdSet().size());
                    collector.collect(tradeFullOrderBean);


                }
            }
        });

        //聚合
      /*  SingleOutputStreamOperator<TradeFullOrderBean> reduceDS = windowDS.reduce(new ReduceFunction<TradeFullOrderBean>() {
            @Override
            public TradeFullOrderBean reduce(TradeFullOrderBean v1, TradeFullOrderBean v2) throws Exception {
                v1.getOrderIdSet().addAll(v2.getOrderIdSet());
                v1.getUserIdSet().addAll(v2.getUserIdSet());
                v1.setOrderAmount(v1.getOrderAmount() + v2.getOrderAmount());
                return v1;
            }
        }, new AllWindowFunction<TradeFullOrderBean, TradeFullOrderBean, TimeWindow>() {
            @Override
            public void apply(TimeWindow timeWindow, Iterable<TradeFullOrderBean> iterable, Collector<TradeFullOrderBean> collector) throws Exception {
                String stt = DateFormatUtil.toYmdHms(timeWindow.getStart());
                String edt = DateFormatUtil.toYmdHms(timeWindow.getEnd());
                for (TradeFullOrderBean fullOrderBean : iterable) {
                    fullOrderBean.setStt(stt);
                    fullOrderBean.setEdt(edt);
                    fullOrderBean.setTs(System.currentTimeMillis());
                    fullOrderBean.setOrderCount((long) fullOrderBean.getOrderIdSet().size());
                    fullOrderBean.setUserCount((long) fullOrderBean.getUserIdSet().size());
                    collector.collect(fullOrderBean);


                }
            }
        });*/

        //写到clickhouse
        reduceDS.print();
        reduceDS.addSink(
                MyClickhouseUtil.getSinkFunction("insert into dws_trade_full_order_window values(?,?,?,?,?,?)")
        );
        env.execute();

    }

}